<template>
  <div class="crud-filter">
    <el-form :model="form">
      <el-row>
        <el-col
            v-for="(option, index) in options"
            :key="option.field"
            :sm="24"
            :md="12"
            :lg="8"
            :xl="6">
          <el-form-item :label="option.title + ':'" style="padding-left: 10px;padding-right: 10px;">
            <component
                :is="option.component.name"
                v-model="form[index].value"
                v-bind="option.component.attrs"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="24"
                :md="12"
                :lg="8"
                :xl="6"
                style="text-align: right;margin-left: auto;">
          <el-button type="success" @click="change">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script setup lang="ts">
import {ref, PropType} from 'vue';
import type {FilterCondition} from '../types';
import cloneDeep from 'lodash-es/cloneDeep';
import isArray from "lodash-es/isArray";

defineOptions({
  name: 'CrudFilter',
});

const props = defineProps({
  options: {
    type: Array as PropType<FilterCondition[]>,
    required: true
  }
});

const form = ref<FilterCondition[]>(cloneDeep(props.options));

// 定义 change 事件
const emits = defineEmits<{
  (e: 'change', filters: FilterCondition[]): void;
}>();

function reset() {
  // 使用 lodash 的 cloneDeep 进行深拷贝
  form.value = cloneDeep(props.options);
  emits('change', form.value);
}

function change() {
  const filters: FilterCondition[] = []
  form.value.forEach((item) => {
    if (isArray(item.fields)) { // 处理起始时间类筛选
      item.fields.forEach((field:string, index: number) => {
        if (isArray(item.operators)) {
          filters.push({
            ...item,
            field,
            operator: item.operators[index],
          })
        } else {
          throw new Error('operators is not array');
        }
      });
    } else {
      filters.push(item);
    }
  });
  emits('change', filters);
}
</script>

<style scoped>
.crud-filter {
  padding: 12px;
  border-radius: 4px;
}
</style>
